<template>
  <basic-container>
    <el-dialog :append-to-body="true" :before-close="cancelDialog" :close-on-click-modal="false"
               title="服务费支付管理" :visible.sync="dialog" custom-class="ledger" fullscreen top="5vh"
               width="1200px">
      <div class="colums">
        <div class="colums_left">
          <div class="colums_left_middle">
            <div class="middleForm ledger">
              <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
                <div class="title">项目信息</div>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label-width="100px" label="合同名称:" prop="projectName">
                      <el-input v-model="form.contractName" placeholder="合同名称" :rules="{required: true, message: '合同名称不能为空', trigger: ['focus', 'change']}"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label-width="100px" label="总金额:" prop="projectName">
                      <el-input-number v-model="form.totalAmount" v-thousand :min="0" style="width: 150px"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label-width="100px" label="批次:" prop="projectName">
                      <el-input-number v-model="form.batch" :min="0" style="width: 150px"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <div class="title">支付项目</div>
                <el-row>
                  <el-col>
                    <el-button icon="el-icon-plus" size="small" type="primary" @click="showProjectDialog()">新增</el-button>
                    <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                    <el-button icon="el-icon-delete-solid" @click="clearTableData">删除全部</el-button>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col>
                    <el-table
                      ref="table"
                      :data="tableData"
                      :model="tableData"
                      style="width: 50%;margin: auto"
                      max-height="450"
                      highlight-current-row
                      @selection-change="updateSelectedRows"
                      @current-change="handleCurrentChange"
                    >
                      <el-table-column type="selection" width="55" align="center"></el-table-column>
                      <el-table-column label="序号" width="100">
                        <template #default="{ $index }">
                          <span>{{ $index + 1 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="项目名称">
                        <template #default="{ row }">
                          <el-input v-model="row.projectName" type="text" disabled></el-input>
                        </template>
                      </el-table-column>
<!--                      <el-table-column label="项目金额">-->
<!--                        <template #default="{ row }">-->
<!--                          <template>-->
<!--                            <el-input-number v-model="row.amount" v-thousand :min="0" style="width: 150px"/>-->
<!--                          </template>-->
<!--                        </template>-->
<!--                      </el-table-column>-->
                    </el-table>
                  </el-col>
                </el-row>
                <div class="title">支付凭证</div>
                <el-row>
                  <el-col>
                    <el-table
                      ref="table"
                      :data="tableFileData"
                      :model="tableFileData"
                      v-loading="loading"
                      style="width: 70%;margin: auto"
                      max-height="450"
                      highlight-current-row
                    >
                      <el-table-column label="序号" width="100">
                        <template #default="{ $index }">
                          <span>{{ $index + 1 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="名称">
                        <template #default="{ row }">
                          <el-input v-model="row.name" type="textarea" :autosize="{ minRows: 1}"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="附件">
                        <template #default="{ row, $index }">
                          <el-upload
                            class="upload-demo"
                            ref="upload"
                            action="/admin/sys-file/upload"
                            :headers="{Authorization}"
                            :on-success="(e) => handleTableSuccess(e, $index)"
                            :on-preview="handlePreview"
                            :on-remove="(file, fileList) => handleTableRemove(file, fileList, $index)"
                            :show-file-list="true"
                            :file-list="row.fileList">
                            <i class="el-icon-paperclip" style="color: #409EFF;"></i>
                          </el-upload>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
                <div class="title" v-if="form.status >1">审核备注</div>
                <el-row>
                  <el-col>
                    <el-form-item label-width="100px" label="合同名称:" prop="projectName" v-if="form.status >1">
                      <el-input v-model="form.remark" placeholder="审核备注" type="textarea" disabled></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
                <el-button icon="el-icon-check" size="small" type="primary" @click="saveCharge" :loading="loading">保存</el-button>
                <el-button icon="el-icon-check" size="small" type="primary" @click="submitCharge" :loading="loading">提交</el-button>
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <ChoseProject ref="ChoseProject" :projectDialog="projectDialog" @cancelDialog="closeProjectDialog" @setValue="projectDataHandle"/>
  </basic-container>
</template>


<script>
import ChoseProject from "@/components/audited/ChoseProject.vue";
import {getCharge,submit,submitCharge} from "@/api/adis/engineering/charge";
import {getByProjectId} from "@/api/adis/execute/discover";
import WebDocument from "@/components/form/webDocument.vue";

export default {
  components: {WebDocument, ChoseProject},
  // props: {
  //   dialog: Boolean,
  // },
  dictTypes: ['audit_type_1_sub'],
  data(){
    return{
      isHidden:true,
      dialog: false,
      form:{
        employmentDates:[]
      },
      projectDialog:false,
      isView:false,
      tableData:[],
      tableFileData:[{name:'合同'},{name:'费用明细表'},{name:'电子发票'}],
      formDisplay:false,
      pageType:'reportOpinion',
      reportHidden:true,
      loading: false,
      Authorization:'',
      fileList:[],
      newRow:{},
      projectIds:[]
    }
  },
  created() {
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    /**表格处理*/
    onAddItem(val) {
      // 在这里添加添加新项目的逻辑
      if (!this.tableData) this.tableData = []
      this.tableData.push(val);
      this.projectIds.push(val.projectId)
    },
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
            this.projectIds.splice(index,1)
          }
        });
        this.selectedRows = [];
        if (this.tableData.length>0){
          this.tableData.forEach((item,i)=>{
            item.number = ++i;
          })
        }
        console.log(this.tableData);
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
      this.projectIds = [];
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },
    handleCurrentChange(selection){
      this.selectedRow = selection;
    },
    /**项目选择页面*/
    showProjectDialog() {
      this.projectDialog = true
      this.$refs.ChoseProject.initParams({
        hasReportFinal: true,//已生成审核终稿且审批完成
        hasNotCharge: true,//未创建服务费
        isEngineering: true, //是否是工程审计
        projectIds: this.projectIds
      });
    },
    closeProjectDialog() {
      this.projectDialog = false
      console.log(this.form)
    },
    projectDataHandle(row){
      this.projectDialog = false;
      // this.newRow.projectId = row.projectId;
      // this.newRow.projectName = row.projectName;
      this.onAddItem(row);
    },
    init(row,isHidden){
      this.isHidden = isHidden;
      this.$nextTick(async () => {
        if (row.chargeId) {
          const response = await getCharge(row.chargeId);
          this.form = response.data.data;
          this.$set(this, 'tableFileData', this.form.serviceChargeAttachmentDTOS)
          this.tableFileData.forEach((item, i) => {
            item.fileList = [];
            item.attachments.forEach(col => {
              item.fileList.push({name: col.fileName, url: col.fileUrl})
            })
          })
          this.tableData = this.form.projectList || [];
        }
        this.dialog = true;
      })
    },
    cancelDialog(){
      this.dialog = false;
      this.form = {};
      this.fileList = [];
      this.clearTableData();
      this.$emit('cancelDialog', {})
    },
    saveCharge() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.projectList = []
          this.tableData.forEach((item, i) => {
            this.form.projectList.push(item)
          })
          this.form.serviceChargeAttachmentDTOS = []
          console.log(this.tableFileData);
          this.tableFileData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList) {
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.serviceChargeAttachmentDTOS.push(item)
          })
          console.log(this.form);
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loading = false;
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitCharge(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.projectList = []
          this.tableData.forEach((item, i) => {
            this.form.projectList.push(item)
          })
          this.form.serviceChargeAttachmentDTOS = []
          this.tableFileData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList) {
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.serviceChargeAttachmentDTOS.push(item)
          })
          this.form.isEngineering = 1;
          this.loading = true;
          submitCharge(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loading = false;
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 文件上传
     */
    handleSuccess(response, file, fileList){
      console.info(response);
      if (!this.fileList) {
        this.fileList = [{url: response.data.url, name: response.data.fileName}]
      } else {
        this.fileList.push({url: response.data.url, name: response.data.fileName})
      }
    },
    handleTableSuccess(e, v) {
      if (!this.tableFileData[v].fileList) {
        this.tableFileData[v].fileList = [{url: e.data.url, name: e.data.fileName}]
        console.log(this.tableFileData);
      } else {
        this.tableFileData[v].fileList.push({url: e.data.url, name: e.data.fileName})
        console.log(this.tableFileData);
      }
    },
    handleRemove(file, fileList,i) {
      this.fileList.forEach((item, v) => {
        console.log(111);
        if (file.url === item.url) this.fileList.splice(v, 1)
      })
    },
    handleTableRemove(file, fileList,i){
      this.tableFileData[i].fileList.forEach((item, v) => {
        if (file.url === item.url) this.tableFileData[i].fileList.splice(v, 1)
      })
    },
    handlePreview(file) {
      const a = document.createElement('a');
      let url = file.url ? file.url : file.response.data.url;
      console.log(url);      // let fileName = '你想要的文件名.docx'; // 这里设置你想要的文件名，包括扩展名
      a.setAttribute('download', file.name);
      a.setAttribute('href', url);
      a.click();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
  }
}
</script>
<style>

</style>
